package small.common.designPattern.behavioral.chainOfResponsibility.slotchain;

public class DefaultProcessorSlotChain extends ProcessorSlotChain{

    /**
     * 首节点
     */
    AbstractLinkedProcessorSlot<?> first = new AbstractLinkedProcessorSlot<Object>()  {
        @Override
        public void entry(Object resource)throws Throwable{
            super.fireEntry(resource);
        }

        @Override
        public void exit(Object resource)throws Throwable {
            super.fireExit(resource);
        }
    };

    /**
     * 尾节点
     */
    AbstractLinkedProcessorSlot<?> end = first;

    @Override
    public void entry(Object resource)throws Throwable{
        first.transformEntry(resource);
    }

    @Override
    public void exit(Object resource)throws Throwable {
        first.transformExit(resource);
    }

    @Override
    public void addFirst(AbstractLinkedProcessorSlot<?> protocolProcessor) {
        protocolProcessor.setNext(first.getNext());
        first.setNext(protocolProcessor);
        if ( end == first){
            end = protocolProcessor;
        }
    }

    @Override
    public void addLast(AbstractLinkedProcessorSlot<?> protocolProcessor) {
        end.setNext(protocolProcessor);
        end = protocolProcessor;
    }

    @Override
    public void setNext(AbstractLinkedProcessorSlot<?> next){
        addLast(next);
    }

    @Override
    public AbstractLinkedProcessorSlot<?> getNext() {
        return first.getNext();
    }


    public AbstractLinkedProcessorSlot<?> getFirst() {
        return first;
    }

    public AbstractLinkedProcessorSlot<?> getEnd() {
        return end;
    }
}
